//
//  PlayerContentViewController.m
//  AVPlayerDemo
//
//  Created by HN on 2021/6/4.
//

#import "PlayerContentViewController.h"

#import "Utility.h"
#import "UIImageView+WebCache.h"
#import "SDImageCache.h"

@interface PlayerContentViewController ()<VideoPlayerDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *preImageView;
@property (weak, nonatomic) IBOutlet UILabel *indexLabel;
@property (weak, nonatomic) IBOutlet UILabel *tipLabel;
@property (weak, nonatomic) IBOutlet UITextView *textView;
@property (weak, nonatomic) IBOutlet UIView *containtView;
@property (weak, nonatomic) IBOutlet UIButton *backButton;
@property (weak, nonatomic) IBOutlet UIView *playerStatusBar;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *playerStatusBarConstraintB;

@property (strong, nonatomic) VideoPlayer *player;

/// 视频宽度
@property(assign, nonatomic) CGFloat videoWidth;
/// 视频高度
@property(assign, nonatomic) CGFloat videoHeight;

@end

@implementation PlayerContentViewController

#pragma mark - life
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self settingPlayer];
    [self setPreImageViewUI];
    [self settingUI];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
//    NSLog(@"\n---------\n%li>>>>>>>viewDidDisappear\n---------\n",(long)self.index);
    if (self.player) {
        [self.player pause];
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
//    NSLog(@"\n---------\n%li>>>>>>>viewDidAppear\n---------\n",(long)self.index);
    if (self.player) {
        [self.player play];
    }
}

- (void)dealloc {
//    NSLog(@"\n---------\n%li>>>>>>>%s\n---------\n",(long)self.index,__func__);
    NSLog(@"%s",__func__);
    if (self.player) {
        [self.player stop];
        self.player = nil;
    }
}

#pragma mark - UI
- (void)settingUI {
    self.textView.text = self.videoInfo.videoUrl;
    self.indexLabel.text = @(self.playIndex).stringValue;
    self.playerStatusBarConstraintB.constant = SAFEAREA_BTM+49;

    [self.view insertSubview:self.backButton aboveSubview:self.player];
    [self.view insertSubview:self.containtView aboveSubview:self.player];
    [self.view insertSubview:self.playerStatusBar aboveSubview:self.player];
}

- (void)setPreImageViewUI {
    SDWebImageManager *manager = [SDWebImageManager sharedManager];
    NSString *imageUrl = [Utility getFrameImagePathWithVideoPath:self.videoInfo.videoUrl];
    NSString *key = [manager cacheKeyForURL:[NSURL URLWithString:imageUrl]];
    SDImageCache *cache = [SDImageCache sharedImageCache];
    //此方法会先从memory中取。
    UIImage *image = [cache imageFromDiskCacheForKey:key];
    if (image) {
        self.preImageView.image = image;
        
        CGFloat width = image.size.width;
        CGFloat height = image.size.height;
        [self setPreImageViewModeWithWidth:width height:height];
    } else {
        __weak typeof(self) weakSelf = self;
        [self.preImageView sd_setImageWithURL:[NSURL URLWithString:imageUrl] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
            if (image) {
                CGFloat width = image.size.width;
                CGFloat height = image.size.height;
                [weakSelf setPreImageViewModeWithWidth:width height:height];
            }
        }];
    }
}

- (void)setPreImageViewModeWithWidth:(CGFloat)width height:(CGFloat)height {
    if (height / width <= 4 / 3.0) {
        self.preImageView.contentMode = UIViewContentModeScaleAspectFit;
    } else {
        self.preImageView.contentMode = UIViewContentModeScaleAspectFill;
    }
}

- (void)settingPlayer {
    self.player = [[VideoPlayer alloc]initWithUrl:[NSURL URLWithString:self.videoInfo.videoUrl] delegate:self];
    self.player.isFullScreenDisplay = YES;
    self.player.frame = CGRectMake(0, 0, UIScreen.mainScreen.bounds.size.width, UIScreen.mainScreen.bounds.size.height);
    [self.view addSubview:self.player];
    
    // 设置视频分辨率
    SDWebImageManager *manager = [SDWebImageManager sharedManager];
    NSString *imageUrl = [Utility getFrameImagePathWithVideoPath:self.videoInfo.videoUrl];
    NSString *key = [manager cacheKeyForURL:[NSURL URLWithString:imageUrl]];
    SDImageCache *cache = [SDImageCache sharedImageCache];
    UIImage *image = [cache imageFromDiskCacheForKey:key];
    if (image) {
        CGFloat width = image.size.width;
        CGFloat height = image.size.height;
        [self setPlayerModeWithWidth:width height:height];
    } else {
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            NSDictionary *options = @{AVURLAssetPreferPreciseDurationAndTimingKey:@YES};
            AVURLAsset *anAsset = [[AVURLAsset alloc] initWithURL:[NSURL URLWithString:self.videoInfo.videoUrl] options:options];
            NSArray *tracks = [anAsset tracksWithMediaType:AVMediaTypeVideo];
            if ([tracks count] > 0) {
                AVAssetTrack *videoTrack = [tracks objectAtIndex:0];
                CGFloat width = videoTrack.naturalSize.width;
                CGFloat height = videoTrack.naturalSize.height;
                CGAffineTransform t = videoTrack.preferredTransform;//这里的矩阵有旋转角度，转换一下即可
                if ([self isVideoPortrait:t] == NO) {
                    self.videoHeight = height;
                    self.videoWidth = width;
                } else {
                    self.videoWidth = height;
                    self.videoHeight = width;
                }
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self setPlayerModeWithWidth:self.videoWidth height:self.videoHeight];
                });
            }
        });
    }
}

- (void)setPlayerModeWithWidth:(CGFloat)width height:(CGFloat)height {
    if (height / width <= 4 / 3.0) {
        self.player.mode = VideoPlayerGravityResizeAspect;
    } else {
        self.player.mode = VideoPlayerGravityResizeAspectFill;
    }
}

- (BOOL)isVideoPortrait:(CGAffineTransform)t {
    BOOL isPortrait = NO;
    // Portrait
    if (t.a == 0 && t.b == 1.0 && t.c == -1.0 && t.d == 0) {
        isPortrait = YES;
    }
    // PortraitUpsideDown
    if (t.a == 0 && t.b == -1.0 && t.c == 1.0 && t.d == 0) {
        isPortrait = YES;
    }
    // LandscapeRight
    if (t.a == 1.0 && t.b == 0 && t.c == 0 && t.d == 1.0) {
        isPortrait = NO;
    }
    // LandscapeLeft
    if (t.a == -1.0 && t.b == 0 && t.c == 0 && t.d == -1.0) {
        isPortrait = NO;
    }
    return isPortrait;
}

//加载动画
- (void)startLoadingPlayItemAnim:(BOOL)isStart {
    if (isStart) {
        self.playerStatusBar.backgroundColor = UIColor.whiteColor;
        self.playerStatusBar.hidden = NO;
        [self.playerStatusBar.layer removeAllAnimations];
        
        CAAnimationGroup *animationGroup = [[CAAnimationGroup alloc]init];
        animationGroup.duration = 0.5;
        animationGroup.beginTime = CACurrentMediaTime()-0.5;
        animationGroup.repeatCount = MAXFLOAT;
        animationGroup.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];

        CABasicAnimation * scaleAnimation = [CABasicAnimation animation];
        scaleAnimation.keyPath = @"transform.scale.x";
        scaleAnimation.fromValue = @(1.0f);
        scaleAnimation.toValue = @(1.0f * [UIScreen mainScreen].bounds.size.width);

        CABasicAnimation * alphaAnimation = [CABasicAnimation animation];
        alphaAnimation.keyPath = @"opacity";
        alphaAnimation.fromValue = @(1.0f);
        alphaAnimation.toValue = @(0.5f);
        [animationGroup setAnimations:@[scaleAnimation, alphaAnimation]];
        [self.playerStatusBar.layer addAnimation:animationGroup forKey:nil];
    } else {
        [self.playerStatusBar.layer removeAllAnimations];
        self.playerStatusBar.hidden = YES;
    }
}

#pragma mark - other
- (IBAction)onActionBack:(UIButton *)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - VideoPlayerDelegate
- (void)videoPlayer:(VideoPlayer *)player playerStatus:(VideoPlayerStatus)status error:(NSError *)error {
    [Utility videoPlayer:player
            playerStatus:status
                   error:error
                tipLabel:self.tipLabel];
    // 第一次加载动画可能无法显示
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (status == VideoPlayerStatusUnknown) {
            [self startLoadingPlayItemAnim:NO];
        } else if (status == VideoPlayerStatusReady) {
            [self startLoadingPlayItemAnim:YES];
        } else if (status == VideoPlayerStatusPlaying) {
            [self startLoadingPlayItemAnim:NO];
        } else if (status == VideoPlayerStatusFailed) {
            [self startLoadingPlayItemAnim:NO];
        } else if (status == VideoPlayerStatusFinished) {
            //
        }
    });
    
    
}

- (void)videoPlayer:(VideoPlayer *)videoPlayer loadingDataWithStatus:(BOOL)isHide {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (videoPlayer.status == VideoPlayerStatusPlaying) {
        }

    });
}
@end
